package com.dreamchaser.familydevice.util.device;

import com.dreamchaser.familydevice.constant.DeviceCache;
import com.dreamchaser.familydevice.domain.dto.DeviceExpression;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.generic.RET;
import org.springframework.data.redis.core.StringRedisTemplate;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class DeviceDataUtil {
    /***
     * 存储每一个客户端接入进来时的Channel对象
     */
    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 设备号，channel id
     */
    private static ConcurrentHashMap<ChannelId, Integer> channelMap = new ConcurrentHashMap();


    public static void remove(Channel channel) {
        channelMap.remove(channel.id());
        group.remove(channel);

    }

    public static void add(Channel channel) {
        channelMap.put(channel.id(), -1);
        group.add(channel);

    }

    public static int getDeviceCode(Channel channel) {
        int deviceKey = channelMap.get(channel.id());
        return deviceKey;
    }

    public static Channel getDeviceChannel(int deviceCode) {
        for (Map.Entry<ChannelId, Integer> entry : channelMap.entrySet()) {
            if (entry.getValue() == deviceCode) {
                return group.find(entry.getKey());
            }

        }
        return null;
    }


    public static boolean setDeviceKey(Channel channel, int deviceKey) {
        Integer device = channelMap.get(channel.id());
        if (device == null) {
            System.out.println("设备注册异常，未知设备");
        }
        channelMap.put(channel.id(), deviceKey);
        return true;
    }

    public static void send(int deviceId, int[] data) {
        for (Map.Entry<ChannelId, Integer> item : channelMap.entrySet()) {
            if (item.getValue() == deviceId) {
                Channel channel = group.find(item.getKey());
                if (channel == null) {
                    log.error("设备组中未找到" + deviceId + "号设备");
                    return;
                }
                log.info("发送数据：" + ByteHexUtil.hexToHexStr(data[0]) + "  到" + deviceId + "号设备");
                ByteBuf d = ByteBufUtil.hexToByteBuf(data);
                channel.writeAndFlush(d);
                return;
            }
        }
        log.error("未找到" + deviceId + "号设备");

    }

    public static void close() {
        group.close().awaitUninterruptibly();
    }

    /**
     * 根据设备号获取设备表达式
     *
     * @param deviceCode
     * @return
     */
    public static DeviceExpression getDeviceExpressionBydeviceCode(int deviceCode) {
        for (DeviceExpression deviceExpression : DeviceCache.ComExperssion) {
            if (deviceExpression.getDeviceCode() == deviceCode) {
                return deviceExpression;
            }
        }
        return null;
    }

    /**
     * 移除任务
     *
     * @param name
     */
    public static void removeTask(String name, StringRedisTemplate redisTemplate) {
        for (String s : DeviceCache.taskName.keySet()) {
            if (s.startsWith(name)) {
                DeviceCache.taskName.remove(s);
                redisTemplate.delete(s);
            }
        }


    }

    /**
     * 根据设备号，组件，组件状态生成变量名
     *
     * @return
     */
    public static String generateVarNameByDeviceAndComStatus(int deviceCode, byte b) {
        return "D" + ByteHexUtil.hexToHexStr(deviceCode) + ByteHexUtil.bytesToHexStr(b);
    }
}
